﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StockHelper.Scripts.Comm
{
    public class Http
    {
        /// <summary>
        /// GET访问
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Get(string url, Hashtable param = null) {
            if (param != null) 
                url = BuildUrl(param, url);
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Referer = "https://finance.sina.com.cn/";


            //req.Headers.Add("referer", "https://finance.sina.com.cn/");



            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                using (StreamReader reader = new StreamReader(stream , Encoding.Default))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            return result;
        }

        /// <summary>
        /// POST访问
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string Post(string url, Hashtable param = null)
        {
            string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/json";
                req.Timeout = 800;//请求超时时间
                byte[] data = Encoding.UTF8.GetBytes(MiniJSON.jsonEncode(param));
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.Default))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch { }
            return result;
        }

        public static string Post(string url, string postData)
        {
            string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.Timeout = 800;
                byte[] data = Encoding.UTF8.GetBytes(postData);
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception e) { Console.WriteLine(e); }
            return result;
        }

        private static string BuildUrl(Hashtable param = null, string url = "")
        {
            if (param == null) return url;
            if (!string.IsNullOrEmpty(url))
            {
                if (url.Contains("?"))
                {
                    if (url.Substring(url.Length - 1) != "&") url += "&";
                }
                else url += "?";
            }
            foreach (string key in param.Keys)
            {
                string val = System.Web.HttpUtility.UrlEncode(param[key].ToString());
                url += key + "=" + val + "&";
            }
            return url.Substring(0, url.Length - 1);
        }

        public static void DownloadList(List<string> list, Action call = null) {
            File.Mkdir(@"voices\downloads");
            Thread thread = new Thread(new ThreadStart(()=> {
                foreach (string url in list) {
                    Uri uri = new Uri(url);
                    if (uri.IsFile) {
                        string filename = System.IO.Path.GetFileName(uri.LocalPath);
                        string path = @"voices\downloads\" + filename.Substring(0, 2);
                        File.Mkdir(path);
                        path += "\\" + filename;
                        HttpDownloadFile(url, path);
                    }
                }
                call?.Invoke();
            }));
            thread.Start();
        }




        /// <summary>
        /// Http下载文件
        /// </summary>
        public static string HttpDownloadFile(string url, string path,Action<string> call = null)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            //创建本地文件写入流
            Stream stream = new FileStream(path, FileMode.Create);
            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            stream.Close();
            responseStream.Close();
            call?.Invoke(path);
            return path;
        }

    }
}
